<?php 
class Upload{
	//允许的类型
	private $allowType;
	//上传路径
	private $path;
	//保存错误信息
	public $error;
	//大小
	private $size;
	
	/**
	 * 初始化函数
	 */
	public function __construct($path=NULL,$allowType=NULL,$size=NULL){
		$this->path = is_null($path) ? C('UPLOAD_PATH') : $path;
		$this->allowType = is_null($allowType) ? C('UPLOAD_ALLOWTYPE') : $allowType;
		$this->size = is_null($size) ? C('UPLOAD_SIZE'): $size;
	}
	
	
	/**
	 * 上传
	 */
	public function up(){
		//1.重组数组
		$arr = $this->reset_arr();
		//2.筛选
		foreach ($arr as $v) {
			//如果有一个不合格
			if(!$this->filter($v)){
				return false;
			}
		}
		//如果能走到下面，则证明全部合格，然后依次上传
		foreach ($arr as $v) {
			$this->move($v);
		}
		return true;
	}
	
	private function reset_arr(){
		// var_dump($_FILES);die;
		$arr = array();
		foreach ($_FILES as $v) {
			if(is_array($v['name'])){
				foreach ($v['name'] as $key => $value) {
					$arr[] = array(
						
						'name' 	=> $value,
						'tmp_name'=>$v['tmp_name'][$key],
						'error'=> $v['error'][$key],
						'type'=> $v['type'][$key],
						'size'=> $v['size'][$key],
					);
				}
			}else{
				$arr[] = $v;
			}
			
		}
		return $arr;
	}
	
	/**
	 * 筛选
	 */
	private function filter($v){
		$type = ltrim(strrchr($v['name'], '.'),'.');
		switch (true) {
			//没有文件上传
			case $v['error'] == 4 :
				$this->error = '没有文件上传';
				return false;
			//1.是否是合法上传文件
			case !is_uploaded_file($v['tmp_name']):
				$this->error = '不是一个合法上传文件';
				return false;
			//2.类型不允许
			case !in_array($type, $this->allowType):
				$this->error = '上传类型不允许';
				return false;
			//3.大小不允许
			case $v['size'] > $this->size:
				$this->error = '上传文件超过网站配置大小';
				return false;
			//4.4种错误
			case $v['error'] == 1 :
				$this->error = '大小超过了 php.ini 中 upload_max_filesize 限制值';
				return false;
			case $v['error']==2:
			    $this->error='大小超过了 html表单中MAX_FILE_SIZE选项制定的值';
				return false;
			case $v['error']==3:
			    $this->error='文件只有部分被上传';
				return false;
			default:
				return true;
		}
		
	}
	
	/**
	 * 移动上传
	 */
	private function move($v){
		$path = rtrim(str_replace('\\', '/', $this->path),'/');
		is_dir($path) || mkdir($path,0777,true);
		$type = ltrim(strrchr($v['name'], '.'),'.');
		//组合路径
		$dest = $path . '/' . time() . mt_rand(0, 9999) . '.' . $type;
		// echo $dest;die;
		$_SESSION['dest']=$dest;
		// var_dump($dest);die;
		$_SESSION['image'] = "<img src='". __UPLOAD__.'/'. basename($dest). " '/>";
		//移动上传
		move_uploaded_file($v['tmp_name'], $dest);
	}
	
	
	
	
	
}




 ?>